package org.com.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import org.com.pojo.Users;
import org.com.pojo.UserBalance;
import org.com.pojo.Transactions;
import org.com.service.UsersService;
import org.com.service.UserBalanceService;
import org.com.service.TransactionsService;
import org.com.util.AliOssUtil;
import org.com.util.AliSmsUtil;
import org.com.util.RedisUtil;
import org.com.util.ValidateCodeUtils;
import org.com.common.R;
import org.com.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

@Api(tags = "角色管理")
@RestController
public class UserController {
    @Autowired
    private UsersService userService;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private RedisUtil redis;
    @Autowired
    private UserBalanceService userBalanceService;
    @Autowired
    private TransactionsService transactionsService;
    private static final String SMS_KEY_PRIFIX = "sms:code:phone:"; //定义验证码key前缀
    private static final String UID_KEY = "uid:"; //定义验证码key前缀

    // 用户注册
    @PostMapping("/addUser")
    public R addUser(@RequestBody Users user, @RequestParam("code") String code) {
        boolean result = userService.addUser(user, code);
        if (result) {
            return R.success("注册成功");
        } else {
            return R.error("注册失败，请检查手机号或用户名是否重复");
        }
    }

    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> loginData, HttpSession session) {
        String username = loginData.get("username");
        String password = loginData.get("password");
        UserVO userVO = userService.login(username, password);
        if (userVO != null) {
            session.setAttribute("userId", userVO.getUserId());
            return R.success("登录成功", userVO);
        }
        // 检查用户是否存在
        Users user = userService.lambdaQuery().eq(Users::getUserName, username).one();
        if (user != null && user.getStatus() != null && user.getStatus() == 0) {
            return R.error("账号已被禁用，请联系管理员");
        }
        return R.error("用户名或密码错误");
    }

    @GetMapping("/logout")
    public R logout(HttpSession session) {
        session.invalidate();
        return R.success("退出登录成功");
    }

    //验证手机号
    @GetMapping("/sendMsg")
    public R sendMsg(@RequestParam String phone) throws Exception {
        System.out.println("我被调用咯");
        if (StringUtils.isEmpty(phone)) {
            return R.error("手机号不能为空");
        }
        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        System.out.println(code);
        System.out.println(phone);
        AliSmsUtil.sendMsgCode(phone, code);//不要删除
        redis.set(SMS_KEY_PRIFIX + phone, code.toString(), 301);
        return R.success("验证码发送成功");
    }

    //  找回密码
    @PostMapping("/findPassword")
    public R findPassword(@RequestBody Map<String, String> params) {
        String phone = params.get("phone");
        String username = params.get("username");
        String newPassword = params.get("newPassword");
        
        boolean result = userService.findPassword(phone, username, newPassword);
        if (result) {
            return R.success("密码修改成功");
        } else {
            return R.error("手机号或用户名错误");
        }
    }

    @PostMapping("/userUpdateApplyType")
    public R userUpdateApplyType(
            HttpServletRequest request,
            @RequestParam(defaultValue = "3") Integer roleId,
            @RequestParam(defaultValue = "0") Integer applyType) {

        // 从session中获取用户ID
        Integer userId = (Integer) request.getSession().getAttribute("userId");
/*        System.out.println("888888"+userId);*/
        boolean result = userService.userUpdateApplyType(userId, roleId, applyType);

        if (result) {
            return R.success("申请已提交，请等待审核");
        } else {
            return R.error("申请失败，请稍后重试");
        }
    }

    @PostMapping("/adminUpdateApplyType")
    public R adminUpdateApplyType(@RequestParam Integer userId, @RequestParam Integer applyType) {
        boolean result = userService.adminUpdateApplyType(userId, applyType);

        if (result) {
            return R.success("申请状态更新成功");
        } else {
            return R.error("申请状态更新失败");
        }
    }

    @GetMapping("/getApplyTypeUser")
    public R getApplyTypeUser() {
        List<Map<String, Object>> users = userService.getApplyTypeUser();
        return R.success("获取待审核用户列表成功", users);
    }

    @GetMapping("/getUserProfile")
    public R getUserProfile(HttpServletRequest request) {
        // 从session中获取用户ID
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        if (userId == null) {
            return R.error("用户未登录");
        }
        Users user = userService.getUserProfile(userId);
        if (user != null) {
            return R.success("获取用户信息成功", user);
        }
        return R.error("获取用户信息失败");
    }

    @PostMapping("/updateUserProfile")
    public R updateUserProfile(@RequestBody Users user, HttpServletRequest request) {
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        if (userId == null) {
            return R.error("用户未登录");
        }
        user.setUserId(userId);
        boolean result = userService.updateUserProfile(user);
        if (result) {
            return R.success("更新用户信息成功");
        }
        return R.error("更新用户信息失败");
    }

    @PostMapping("/uploadAvatar")
    public R uploadAvatar(MultipartFile image, HttpServletRequest request) {
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        if (userId == null) {
            return R.error("用户未登录");
        }
        try {
            String url = aliOssUtil.upload(image);
            System.out.println("头像上传成功");
            return R.success("上传头像成功", url);

        } catch (Exception e) {
            System.out.println("头像上传失败");
            return R.error("上传头像失败：" + e.getMessage());
        }
    }

    @GetMapping("/getUserBalance")
    public R getUserBalance(HttpServletRequest request) {
        // 从session中获取用户ID
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        if (userId == null) {
            return R.error("用户未登录");
        }
        BigDecimal balance = userBalanceService.getUserBalance(userId);
        return R.success("获取余额成功", balance);
    }

    @GetMapping("/getUserTransactions")
    public R getUserTransactions(HttpServletRequest request) {
        // 从session中获取用户ID
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        if (userId == null) {
            return R.error("用户未登录");
        }
        
        // 获取用户的balance_id
        QueryWrapper<UserBalance> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserBalance userBalance = userBalanceService.getOne(queryWrapper);
        if (userBalance == null) {
            return R.error("未找到用户余额信息");
        }
        
        // 获取交易记录
        List<Transactions> transactions = transactionsService.getUserTransactions(userId, userBalance.getBalanceId());
        return R.success("获取交易记录成功", transactions);
    }

    @GetMapping("/user/list")
    public R getUserList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        // 创建分页对象
        Page<Users> pageInfo = new Page<>(page, pageSize);
        // 执行分页查询，并获取包含用户角色的结果
        Page<Users> result = userService.getUserListWithRoles(pageInfo);
        
        return R.success("获取用户列表成功", result);
    }

    @PutMapping("/user/resetPassword/{userId}")
    public R resetUserPassword(@PathVariable Integer userId) {
        boolean result = userService.resetUserPassword(userId);
        if (result) {
            return R.success("密码重置成功");
        }
        return R.error("密码重置失败");
    }

    @DeleteMapping("/user/{userId}")
    public R deleteUser(@PathVariable Integer userId) {
        boolean result = userService.deleteUserWithRoles(userId);
        if (result) {
            return R.success("用户删除成功");
        }
        return R.error("用户删除失败");
    }

    @PutMapping("/user/status")
    public R updateUserStatus(@RequestBody Map<String, Object> params) {
        Integer userId = (Integer) params.get("userId");
        Integer status = (Integer) params.get("status");
        
        if (userId == null || status == null) {
            return R.error("参数错误");
        }

        boolean result = userService.updateUserStatus(userId, status);
        if (result) {
            return R.success("用户状态更新成功");
        }
        return R.error("用户状态更新失败");
    }
}
